﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _01_课堂练习
{
    public delegate void AlarmHandler(object sender, DateTime args);
    public delegate void TickHandler(object sender, DateTime args);

    class Clock
    {
        /// <summary>
        /// 闹铃的时间
        /// </summary>
        DateTime alarmTime = DateTime.Now;

        public event AlarmHandler OnAlarm;
        public event TickHandler OnTick;

        public Clock()
        {
            OnAlarm += Alarm;
            OnTick += Tick;
        }

        public void Alarm(object sender, DateTime time)
        {
            Console.WriteLine("==========到达设定时间!:" + time + "起床 ============");
        }

        public void Tick(object sender, DateTime time)
        {
            Console.WriteLine("当前时间:" + time);
        }



        /// <summary>
        /// 设置闹铃事件
        /// </summary>
        /// <param name="atime"></param>
        public void SetAlarmTime(DateTime atime)
        {
            Console.WriteLine(atime);
            alarmTime = atime;
        }
        /// <summary>
        /// 启动闹钟
        /// </summary>
        public void Strat()
        {
            while (true)
            {
                DateTime now = DateTime.Now;
                //滴答
                OnTick(this, now);
                if (now.ToString() == alarmTime.ToString())
                {
                    //触发闹铃
                    OnAlarm(this, alarmTime);
                }
                //阻塞防止事件运行太快
                Thread.Sleep(1000);
            }
        }

    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Clock clock = new Clock();
            //获取当前的时间
            DateTime atime = DateTime.Now.AddSeconds(2);//在当前时间的基础上添加两秒
            //设置需要闹铃的时间
            clock.SetAlarmTime(atime);
            //启动闹钟
            clock.Strat();

            Console.ReadKey();
        }
    }
}
